package cn.xyy.system.api;

import java.util.Date;

import cn.xyy.system.service.AuthService;
import cn.xyy.web.AuthUserHolder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import cn.dev33.satoken.stp.StpUtil;
import cn.xyy.common.annotation.log.Log;
import cn.xyy.common.domain.mvc.R;
import cn.xyy.common.domain.system.auth.LoginVO;
import cn.xyy.common.domain.system.auth.ModifyPwdVO;
import cn.xyy.common.domain.system.auth.UserBasicInfoVO;
import cn.xyy.common.domain.system.auth.UserInfo;
import cn.xyy.common.domain.system.log.SysLog;
import cn.xyy.common.spring.SpringContextHolder;
import cn.xyy.common.spring.SpringMVCUtil;
import cn.xyy.common.utils.HttpUtils;
import cn.xyy.log.event.SysLogEvent;

/**
 * 登录认证接口
 * 
 * @author xyy
 *
 */
@RestController
@RequestMapping(value = "/rest/auth")
public class AuthRest {

	@Autowired
	private AuthService authService;

	@Log("登录")
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public R login(@RequestBody LoginVO vo) {
		authService.login(vo);
		return R.ok(StpUtil.getTokenInfo());
	}

	/**
	 * 当前在线用户的信息包括角色权限菜单等
	 *
	 * @param @return 设定文件
	 * @return ResponseResult 返回类型
	 */
	@RequestMapping(value = "getUserInfo")
	public R getUserInfo() {
		return R.ok(authService.getUserInfo());
	}

	@RequestMapping("logout")
	public R logout() {
		SysLog log = new SysLog();
		log.setTimestamps(System.currentTimeMillis());
		log.setCreateTime(new Date());
		log.setStatus(1);
		log.setTitle("退出");
		log.setIp(HttpUtils.getIpAddr(SpringMVCUtil.getRequest()));

		UserInfo user = AuthUserHolder.getUserInfo();
		if (user != null) {
			log.setCreator(user.getUsername());
			AuthUserHolder.destroyUser();

		}
		StpUtil.logout(user.getUid(), StpUtil.getLoginDevice());
		SpringContextHolder.publishEvent(new SysLogEvent(log));
		return R.ok();
	}

	@Log("修改密码")
	@RequestMapping(value = "modifyPwd", method = RequestMethod.POST)
	public R modifyPwd(@RequestBody ModifyPwdVO vo) {
		authService.modifyPwd(vo);
		return R.ok();

	}

	@Log("更新基本信息")
	@RequestMapping(value = "updateBasicInfo", method = RequestMethod.POST)
	public R updateBasicInfo(@RequestBody UserBasicInfoVO vo) {
		authService.updateBasicInfo(vo);
		return R.ok();
	}
}
